<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="my-tool-bar">
        <Toolbar :items="pageData.btnList" @add="addHandler" @select="selectHandler" @downloadApp="downloadApp">
        </Toolbar>
      </div>
    </template>

    <template #pageTabel>
      <div class="w-full h-full">
        <encapsulation-agrid style="height: 100%" ref="gridOption" :configaggrid="configTable"></encapsulation-agrid>
      </div>
    </template>

    <a-drawer ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 9999 }" :mask-closable="false" :width="500"
      :ok-loading="pageData.pageLoading" :visible="pageData.showAdd" unmountOnClose @ok="sideOk"
      @cancel="pageData.showAdd = false">
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <a-form-item label-col-flex="90px" label="版本号" field="versionCode"
            :rules="[{ required: true, message: '版本号必填' }]" :validate-trigger="['change', 'blur']">
            <a-input class="bacClass" v-model="dataForm.versionCode" />
          </a-form-item>

          <a-form-item label-col-flex="90px" label="版本名称" field="versionName"
            :rules="[{ required: true, message: '版本名称必填' }]" :validate-trigger="['change', 'blur']">
            <a-input class="bacClass" v-model="dataForm.versionName" />
          </a-form-item>

          <a-form-item label-col-flex="90px" label="版本信息" field="versionInfo"
            :rules="[{ required: true, message: '版本信息必填' }]" :validate-trigger="['change', 'blur']">
            <a-input class="bacClass" v-model="dataForm.versionInfo" />
          </a-form-item>

          <a-form-item label-col-flex="90px" label="备注" field="remark">
            <a-input class="bacClass" v-model="dataForm.remark" />
          </a-form-item>

          <a-form-item label-col-flex="90px" label="安装包" field="file">
            <a-upload action="/" :limit="1" accept=".exe" :customRequest="customUpload1" />
          </a-form-item>

          <a-form-item label-col-flex="90px" label="配置文件" field="file">
            <a-upload action="/" :limit="1" accept=".yml" :customRequest="customUpload2" />
          </a-form-item>

          <a-form-item label-col-flex="90px" label="安全验证文件" field="file">
            <a-upload action="/" :limit="1" accept=".blockmap" :customRequest="customUpload3" />
          </a-form-item>

        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts" setup>
import { post, get } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
import emitter from '@/hooks/useEventBus'
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { Button, Form, Message, Modal } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import { baseURL } from '../../api/axios.config'
import axios from 'axios'
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'
import PageTabelLayout from '@/components/pageTabelLayout.vue'
import MyTable from '@/components/MyTable'
import ButtonRenderer from '@/components/TableCellRenderer/ButtonRenderer'
import { template } from 'lodash'
import { setupGlobalComponent } from '@/layouts'
import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import printJS from 'print-js'
import QrcodeVue from 'qrcode.vue'

// 引入

import { Header } from 'element-plus/es/components/table-v2/src/components'

interface PositionList {
  id: any
  versionCode: string | undefined
  versionName: string | undefined
  versionInfo: string | undefined
  applicationUrl: string | undefined
  apkUrl: string | undefined
  file: any[]
}

const total = ref(0)
const page = ref(1)
const size = ref(10)
function PageSize(val: any) {
  page.value = val
  doRefresh()
}
function change1(val: any) {
  size.value = val
  doRefresh()
}
const headerShow = ref<boolean>(true)

function doRefresh() {
  try {
    gridOption.value.setQuery({
    })
  } catch (error) {
    console.log(error);
  }
}
const optionsList: any = ref(pagingList)

const { selectedRowKeys, onSelectionChange } = useRowSelection()
const pagination = usePagination(doRefresh)
const table = useTable()
const rowKey = useRowKey('id')
const tableColumns = useTableColumn([
  {
    title: '版本号',
    key: 'versionCode',
    dataIndex: 'versionCode',
    width: 150,
  },

  {
    title: '版本名称',
    key: 'versionName',
    dataIndex: 'versionName',
    width: 150,
  },

  {
    title: '版本信息',
    key: 'versionInfo',
    dataIndex: 'versionInfo',
    width: 150,
  },
  {
    title: '安装包路径',
    key: 'apkUrl',
    dataIndex: 'apkUrl',
    width: 150,
  },
  {
    title: '配置文件地址',
    key: 'applicationUrl',
    dataIndex: 'applicationUrl',
    width: 150,
  },
  {
    title: '更新包路径',
    key: 'safetyUrl',
    dataIndex: 'safetyUrl',
    width: 150,
  },
  {
    title: '创建人',
    key: 'createName',
    dataIndex: 'createName',
    width: 150,
  },
  {
    title: '创建时间',
    key: 'createTime',
    dataIndex: 'createTime',
    width: 200,
  },
  {
    title: '最后修改人',
    key: 'updateName',
    dataIndex: 'updateName',
    width: 150,
  },
  {
    title: '最后修改时间',
    key: 'updateTime',
    dataIndex: 'updateTime',
    width: 200,
  },
])

let tc: any[] = tableColumns.map((o) => {
  let obj = {
    headerName: o.title,
    field: o.key,
    pinned: o['fixed'],
    tooltipField: o.key,
  }
  return obj
})

let a = [
  {
    showRowGroup: 'hide_def',
    headerName: '',
    checkboxSelection: true,
    headerCheckboxSelection: true,
    pinned: 'left',
    width: 50,
    resizable: false,
    filter: false,
    sortable: false,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: 'left',
  },
]

tc = a.concat(tc)
let configTable = ref({
  url: 'qms/version/getPage', //接口路径
  queryData: {},
  // isGet:true,//是否是get请求\
  // isLimit:true,//后端分页接收limit而非size
  paginationShow: true, //分页是否显示
  invokeiIterface: true, //是否调用接
  rowMultiSelectWithClick: false, //点击行是否多选
  column: tc,
  fileName: 'FabricInspectionManagement', //导出文件名
})

interface PageData {
  showAdd: boolean
  sideTitle: string
  nameList: []
  pageLoading: boolean
  typeList: []
  dropDownData1: any
  rHeight: any
  btnList: any[]
  isEdit: boolean
  firmList: any[]
  file: any[]
}

const pageData = reactive<PageData>({
  nameList: [],
  showAdd: false,
  sideTitle: '新增APP版本',
  pageLoading: false,
  typeList: [],
  dropDownData1: '',
  rHeight: 0,
  btnList: [],
  isEdit: false,
  firmList: [],
  file: [],
})

let cxbl = ''
//查询
const selectHandler = () => {
  page.value = 1
  doRefresh()
}

const queryData = reactive({
  clothType: '',
})

const addHandler = () => {
  for (var key in dataForm) {
    if (key === 'id') {
      dataForm[key] = null
    } else if (key === 'file') {
      dataForm[key] = []
    } else {
      dataForm[key] = ''
    }
  }

  pageData.showAdd = true
  pageData.sideTitle = '新增APP版本'
}

const dataForm = reactive<PositionList>({
  id: null,
  versionCode: '',
  versionName: '',
  versionInfo: '',
  applicationUrl: '',
  apkUrl: '',
  file: [],
})

// 表格准备事件
const gridOption = ref()

let formRef = ref<FormInstance>()
const sideOk = () => {
  formRef.value?.validate().then((err) => {
    if (!err) {
      if (!pageData.file[0] || pageData.file[0].length == 0) {
        Message.error({
          content: '请上传安装包',
          duration: 5000,
        })
        return
      }

      const fileNames = ['安装包', '配置文件', '安全验证映射文件'];
      if (!pageData.file[1] || pageData.file[1].length == 0) {
        Message.error({
          content: '请上传配置文件',
          duration: 5000,
        })
        return
      }

      if (!pageData.file[2] || pageData.file[2].length == 0) {
        Message.error({
          content: '请上传安全验证映射文件',
          duration: 5000,
        })
        return
      }

      pageData.pageLoading = true
      try {
        let fd = new FormData()
        fd.append('file', pageData.file[0])
        fd.append('file', pageData.file[1])
        fd.append('file', pageData.file[2])
        pageData.showAdd = true
        axios.post(baseURL + '/minio/file/uploadFileBatchByQms',
          fd,
          {
            headers: {
              'Content-Type': 'multipart/form-data',
              token: sessionStorage.getItem('USER-TOKEN-KEY'),
            },
          })
          .then((res: any) => {
            if (res.data.code === 200) {
              var urlList = res.data.data.data

              if (urlList.length == 3) {
                dataForm.apkUrl = urlList[0]
                dataForm.applicationUrl = urlList[1]
                dataForm.safetyUrl = urlList[2]
              }
              post({
                url: 'qms/version/save',
                data: dataForm,
              })
                .then((res: any) => {
                  if (res.code === 200) {
                    formRef.value?.resetFields()
                    pageData.showAdd = false
                    Message.success({
                      content: '新增成功',
                      duration: 5000,
                    })
                    doRefresh()
                  } else {
                    Message.error({ content: res.message, duration: 5000, })
                  }
                })
                .finally(() => {
                  pageData.pageLoading = false
                })
            } else {
              Message.error({ content: res.message, duration: 5000, })

            }
          })
      } catch (error) {
        pageData.pageLoading = false
      }
    }
  })
}


let curobj = null
const editHandler = (record: PositionList) => {
  curobj = record
  for (let key in record) {
    dataForm[key] = record[key]
  }
  pageData.sideTitle = '修改APP版本'
  pageData.showAdd = true
}

const handleChange = (_data: any) => {
  table.handleSuccess(_data)
}

const defaultColDef = {
  sortable: true,
  resizable: true,
  filter: true,
  // flex: 1
}

const uploadFile = () => { }

//文件上传
function customUpload1(info: any) {
  info.onSuccess('')
  pageData.file[0] = info.fileItem.file

  return info
}

function customUpload2(info: any) {
  info.onSuccess('')

  pageData.file[1] = info.fileItem.file
  return info
}

function customUpload3(info: any) {
  info.onSuccess('')

  pageData.file[2] = info.fileItem.file
  return info
}

//下载安装包
const downloadApp = () => {
  pageData.pageLoading = true
  post({
    url: 'qms/version/getNewApk',
  }).then(({ code, data, message }: any) => {
    if (code === 200) {
      axios
        .get(baseURL + '/minio/file/download/zzy/' + data.apkUrl, {
          responseType: 'blob',
          headers: {
            token: sessionStorage.getItem('USER-TOKEN-KEY'),
            responseType: 'blob',
            'Content-Type': 'multipart/from-data',
          },
        })
        .then((res: any) => {
          if (res.status == 200) {
            const link = document.createElement('a')
            let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' }) //生成blob对象
            link.style.display = 'none'
            link.href = URL.createObjectURL(blob)
            //下载的文件名以及文件格式
            link.setAttribute('download', data.apkUrl)
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          }
        })
        .catch(() => {
          Message.error({
            content: '文件路径不存在，请联系管理员.',
            duration: 5000,
          })
        })
        .finally(() => {
          pageData.pageLoading = false
        })
    } else {
      Message.error({
        content: message,
        duration: 5000,
      })
    }
  })
}

const localeText1: any = ref(localeText)
//设置权限
// ['查询', '新增', '删除', '导出', '导入']
const permissionStore = usePermission()

if (permissionStore.hasPermisson('ybbbgl.cx')) {

  pageData.btnList.push("查询")
}
if (permissionStore.hasPermisson('ybbbgl.xz')) {
  pageData.btnList.push("新增")
}

if (permissionStore.hasPermisson('ybbbgl.xzazb')) {
  pageData.btnList.push("下载安装包")
}

</script>

<style scoped lang="less">
:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}
</style>